﻿using System;
using System.Xml;
using System.Web;

namespace Landscape
{
    class DocumentTemplate : Template
    {
        public string WrapperName;

        public DocumentTemplate(string xmlTemplatePath) : base(xmlTemplatePath)
        {
            XmlNode rootTemplateNode = null;
            XmlNodeList xsltTemplates = TemplateDom.GetElementsByTagName("template", Context.xslNamespace);
            if (xsltTemplates.Count > 0)
            {
                foreach (XmlNode tplNode in xsltTemplates)
                {
                    XmlNode matchAttr = tplNode.Attributes.GetNamedItem("match");
                    XmlNode wrapperAttr = tplNode.Attributes.GetNamedItem("wrapper", Context.lscNamespace);

                    if (matchAttr != null && matchAttr.Value.Equals("/"))
                    {
                        rootTemplateNode = tplNode;
                        if (wrapperAttr != null && !string.IsNullOrEmpty(wrapperAttr.Value))
                        {
                            WrapperName = wrapperAttr.Value;

                            rootTemplateNode.Attributes.RemoveNamedItem("wrapper", Context.lscNamespace);
                            break;
                        }
                    }
                }
            }

            if (rootTemplateNode == null)
            {
                throw new Exception("Template does not contain a root template (<xsl:template match=\"/\"> ... </xsl:template>)");
            }

            if (string.IsNullOrEmpty(WrapperName))
            {
                Renderer.CreateXslOutput(TemplateDom, OutputMethod, Context.outputDocTypePublic, Context.outputDocTypeSystem, "utf-8", true, false, Context.outputIndent, false);
            }
            else
            {
                OutputMethod = OutputMethods.Xml;
                Renderer.CreateXslOutput(TemplateDom, OutputMethod, null, null, "utf-8", true, false, Context.outputIndent, false);
            }

            // create compiled transform object
            TemplateCompiledTransform = Context.Library.compiler.Compile(TemplateDom);
        }

        public static DocumentTemplate GetTemplate(string templatePath)
        {
            if (Context.enableCaching)
            {
                if (HttpRuntime.Cache[templatePath] != null)
                {
                    DocumentTemplate cached = (DocumentTemplate)HttpRuntime.Cache[templatePath];

                    return cached;
                }
            }

            DocumentTemplate template = new DocumentTemplate(templatePath);

            // saves object into cache
            if (Context.enableCaching)
            {
                
                HttpRuntime.Cache.Insert(templatePath, template, new System.Web.Caching.CacheDependency(template.DependenciesPaths.ToArray()));
            }

            return template;
        }
    }
}
